﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TaskFactory_When_ContinueWhenAll.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the TaskFactory_When_ContinueWhenAll type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Threading
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Mocks;
    using Testing.Threading;

    [TestClass]
   public class TaskFactory_When_ContinueWhenAll : AsynchronousTest
   {
      [TestMethod]
      [HostType("CHESS")]
      public void If_All_Completed_From_Different_Threads_Should_Run_Continuation()
      {
         var result = TestStrings.Failure;
         var task1 = Task.Factory.From(MockDelegates.DoNothing);
         var task2 = Task.Factory.From(MockDelegates.DoNothing);
         var task3 = Task.Factory.ContinueWhenAll(new[] {task1, task2},
            t =>
               {
                  if (task1.IsComplete && task2.IsComplete)
                     result = TestStrings.Success;
               });
         task1.Start();
         task2.Start();
         task3.Wait();
         Assert.AreEqual(TestStrings.Success, result);
      }

      [TestMethod]
      public void If_All_Completed_Should_Run_Continuation()
      {
         var continuationRan = false;
         var result = TestStrings.Failure;
         
         var task1 = TestTaskFactories.Synchronous.From(MockDelegates.DoNothing);
         var task2 = TestTaskFactories.Synchronous.From(MockDelegates.DoNothing);
         TestTaskFactories.Synchronous.ContinueWhenAll(new[] { task1, task2 },
            t =>
            {
               if (t[0].IsComplete && t[1].IsComplete)
                  result = TestStrings.Success;
               continuationRan = true;
            });
         
         // assert continuation sequence
         Assert.IsFalse(continuationRan);
         task1.Start();
         Assert.IsFalse(continuationRan);
         task2.Start();
         Assert.IsTrue(continuationRan);
         Assert.AreEqual(TestStrings.Success, result);
      }
   }
}